﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Kay.Nuget.Helper
{
    /// <summary>
    /// 序列化帮助器
    /// </summary>
    public class SerializeHelper
    {
        /// <summary>
        /// Xml 序列化
        /// </summary>
        /// <typeparam name="T">序列化类型</typeparam>
        /// <param name="value">序列化对象</param>
        /// <returns>序列化后的 Xml 内容</returns>
        public static string XmlSerialize<T>(T value)
        {
            if (value == null)
                return string.Empty;
            string xmlString;
            var xmlSerizlizer = new XmlSerializer(typeof(T));
            using (var memoryStream = new MemoryStream())
            {
                xmlSerizlizer.Serialize(memoryStream, value);
                xmlString = Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            return xmlString;
        }

        /// <summary>
        /// 如果字符串是标准 Xml 结构，可以使用此方法反序列化成对应的类
        /// </summary>
        /// <typeparam name="T">反序列化类型</typeparam>
        /// <param name="value">Xml 内容</param>
        /// <returns>反序列化成功的类</returns>
        public static T XmlDeserizlize<T>(string value)
        {
            if (string.IsNullOrEmpty(value) || value.Trim() == string.Empty)
                return default(T);

            T t;
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (var xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(value)))
            {
                using (var xmlReader = XmlReader.Create(xmlStream))
                {
                    try
                    {
                        var obj = xmlSerializer.Deserialize(xmlReader);
                        t = (T)obj;
                    }
                    catch (InvalidOperationException)
                    {
                        throw new InvalidOperationException("序列化失败！");
                    }
                }
            }

            return t;
        }
    }
}